<?php
/**
* sample:
* 
*/
require_once(WEBROOT."web-inf/constant.php");//数据库配置
Class MySql{
	var $conn;
	var $sql;
	private $host;
	private $port;
	private $user;
	private $pwd;
	private $dbname;
	function __construct($host='',$dbname='',$user='',$pwd='',$port=''){
	   //global $Config;
		$this->host=empty($host)?DBURLMAIN:$host;
		$this->user=empty($user)?DBUSER:$user;
		$this->pwd=empty($pwd)?DBPASSWORD:$pwd;
		$this->dbname=empty($dbname)?DBDOMAIN:$dbname;
		$this->conn=@mysql_connect( $this->host, $this->user, $this->pwd) or die("数据连接失败");
		@mysql_select_db($this->dbname, $this->conn) or die("指定的数据库不存在");
		@mysql_unbuffered_query("set names utf8");
	}

	function __destruct(){
		@mysql_close($this->conn);
	}

	function GetAll($field="*",$tablename,$where)
	{
		$query = "select {$field} from {$tablename} where {$where}"; 
		$this->sql=$query;
		$handle = @mysql_query($query,$this->conn);
		if (@mysql_num_rows($handle)>0){
			$RsArray = array();
			while ($rows = mysql_fetch_assoc($handle)){
				$RsArray[] = $rows;
			}
			return $RsArray;
		}
		else{
			return false;
		}
	}

	/*获取所有数据记录
	 * 有键值方式*/
	function GetAllSql($query)
	{
		$this->sql=$query;
		$handle = @mysql_query($query,$this->conn);
		if($handle)
		{
			$RsArray = array();
			while ($rows = mysql_fetch_assoc($handle)){
				$RsArray[] = $rows;
			}
			return $RsArray;
		}
		else{
			return array();
		}
	}

	function GetRows($field="*",$tablename,$where,$num,$start='0')
	{
		$sql = '';
		if ($start == 0)
		{
			$sql .= ' LIMIT ' . $num;
		}
		else
		{
			$sql .= ' LIMIT ' . $start . ', ' . $num;
		}
		$query = "select {$field} from {$tablename} where {$where} {$sql}";
        //echo $query;
		$this->sql=$query;
		$handle = @mysql_query($query,$this->conn);
		if (@mysql_num_rows($handle)>0){
			$RsArray = array();
			while ($rows = mysql_fetch_assoc($handle)){
				$RsArray[] = $rows;
			}
			return $RsArray;
		}
		else{
			return false;
		}
	}

	function GetRowsSql($sql, $num, $start = 0)
	{
		if ($start == 0)
		{
			$sql .= ' LIMIT ' . $num;
		}
		else
		{
			$sql .= ' LIMIT ' . $start . ', ' . $num;
		}
		$this->sql=$sql;
		return $this->query($sql);
	}

	function GetOne($field="*",$tablename,$where)
	{
		$query = "select {$field} from {$tablename} where {$where}"; 
		$this->sql=$query;
		$handle = @mysql_query($query,$this->conn);
		if (@mysql_num_rows($handle)>0){
			return (mysql_fetch_assoc($handle));
		}else{
			return false;
		}
	}

	function GetOneSql($query)
	{
		$this->sql=$query;
		$handle = @mysql_query($query,$this->conn);
		if($handle)
		{
		return (mysql_fetch_assoc($handle));
		}else{
		return array();
		}
	}
    //总条数
    function QueryCount($sql){
		$this->sql=$sql;
        $rult=@mysql_query($sql);
        if($rult){
            $count=@mysql_num_rows($rult);
            if($count){
                return $count;
            }else{
                return false;
            }
        }else{
            return false;
        }        
    }
	function GetNum($tablename,$where='1=1')
	{
		$query = "select count(*) as total from {$tablename} where {$where}"; 
     
		$this->sql=$query;
		$handle = @mysql_query($query,$this->conn);
		if (@mysql_num_rows($handle)>0){
			$reArr = mysql_fetch_assoc($handle);
			return $reArr['total'];
		}else{
			return false;
		}
	}

	function InsertRow($tablename, $queryarray)
	{
		$insertkeysql = $insertvaluesql = $comma = "";
		foreach ( $queryarray as $insert_key => $insert_value )
		{
			$insertkeysql .= $comma."`{$insert_key}`";
			$insertvaluesql .= $comma."'{$insert_value}'";
			$comma = ", ";
		}
		$query = "INSERT INTO {$tablename} ({$insertkeysql}) VALUES ({$insertvaluesql}) ";
		$this->sql = $query;
		@mysql_query($query, $this->conn);
		$id = @mysql_insert_id($this->conn);
		if($id >= 0){
			return $id;
		}else{
			$row = $this->GetOne("SELECT last_insert_id()");
			return $row[0];
		}
	}

	function updateRow($tablename,$query_array,$where){
		$updatesql = $comma = "";
		foreach ($query_array as $update_key=>$update_value){
			$updatesql .= $comma."`{$update_key}` = '{$update_value}'";
			$comma = ", ";
		}
		$query = "UPDATE {$tablename} SET {$updatesql} WHERE {$where} ";
		$this->sql = $query;  
		if(@mysql_query($query, $this->conn)){
			return true;
		}else{
			return false;
		}
	}

	function query($sql){
		$this->sql = $sql;  
		if($query = @mysql_query($sql,$this->conn)){
			$this->rs=$query;
			return $query;
		}else{
			$this->rs=false;
			return false;
		}
	}

	/** 复制表数据
	* @param $sql				string		查询sql
	* @param $unsetParam		array		不需要复制的字段名称组成的数组
	* @param $data				array		需要修改数据
	* @param $toTable			string		目标表名
	* @Return Array				数组
	*/
	function copyData($sql,$unsetParam,$data,$toTable)
	{
		$rows=$this->GetAllSql($sql);
		if(is_array($rows))
		{
			foreach($rows as $k => $row)
			{
				//过滤不需要复制的字段
				if(is_array($unsetParam))
				{
					foreach($unsetParam as $k2 => $v2)
					{
						if(isset($row[$v2]))
						{
							unset($row[$v2]);
						}
					}
				}
				//篡改数据
				if(is_array($data))
				{
					foreach($data as $k2 =>$v2)
					{
						$row[$k2]=$v2;
					}
				}
				//插入新数据
				$rs[]=$this->InsertRow($toTable,$row);
			}
			return $rs;
		}
		else
		{
			return false;
		}
	}

	function affected_rows()
	{
		return mysql_affected_rows($this->conn);
	}

	function error()
	{
		return mysql_error($this->conn);
	}

	function errno()
	{
		return mysql_errno($this->conn);
	}

	function result($query, $row)
	{
		return @mysql_result($query, $row);
	}

	function num_rows($query)
	{
		return mysql_num_rows($query);
	}

	function num_fields($query)
	{
		return mysql_num_fields($query);
	}

	function free_result($query)
	{
		return mysql_free_result($query);
	}

	function insert_id()
	{
		return mysql_insert_id($this->conn);
	}

	function fetchRow($query)
	{
		if($query=='')
		{
			$query=$this->rs;
		}
		return mysql_fetch_assoc($query);
	}

	function fetch_fields($query)
	{
		return mysql_fetch_field($query);
	}

	function version()
	{
		return $this->version;
	}

	function ping()
	{
		if (PHP_VERSION >= '4.3')
		{
			return mysql_ping($this->link_id);
		}
		else
		{
			return false;
		}
	}
	function close()
	{
		return mysql_close($this->link_id);
	}

	function getCol($sql)
	{
		$this->sql = $sql;  
		$res = $this->query($sql);
		if ($res !== false)
		{
			$arr = array();
			while ($row = mysql_fetch_row($res))
			{
				$arr[] = $row[0];
			}

			return $arr;
		}
		else
		{
			return false;
		}
	}
	
	/** 设置待操作表的基本信息
	* @param tbl	表名
	* @param id		主键字段
	*/
	function setTbl($tbl,$key_name='id')
	{
		$this->tbl=$tbl;
		$this->tbl_id=$key_name;
	}
	
	/**
	*查询数据库表的字段
	*/
	function getParam($tbl="")
	{
		if(empty($tbl))
		{
			$tbl=$this->tbl;
		}
		if(empty($tbl))
		{
			die('"表名"未定义');
		}
		$sql="show columns from ".$tbl;
		$rs=$this->query($sql);
		$ss='';
		while($rs && $row=$this->fetchRow($rs))
		{
			if($ss=='')
			{
				$ss=$row['Field'];
			}
			else
			{
				$ss.=','.$row['Field'];
			}
		}
		$this->params=$ss;
		return $ss;
	}
	
	/** 根据字段获取
	* @param id		字段id
	* @param tbl	数据表名称
	* @Return Array
	*/
	function getOneById($id,$tbl="")
	{
		if(empty($tbl))
		{
			$tbl=$this->tbl;
		}
		$sql="select * from $tbl where {$this->tbl_id}='$id'";
		$rs=$this->query($sql);
		if($rs)
		{
			$ss=$this->fetchRow();
		}
		else
		{
			$ss=false;
		}
		return $ss;
	}
	
	/*
	* 插入新数据 使用前必须设定数据库表的"表名","主键名"
	* @param aryValue	待插入的值
	* @param tbl 		表名
	* @Return Integer
	*/
	function Insert($aryValue='',$tbl="")
	{
		if(empty($aryValue))
		{
			$aryValue=$this->value;
		}
		if(empty($tbl))
		{
			$tbl=$this->tbl;
		}
		$sql="insert into $tbl set ";
		$set='';		//初始化插入数据为空
		if(empty($this->params))
		{
			$this->getParam($tbl);
		}
		$aryparam=explode(',',$this->params);
		if(is_array($aryparam))
		{
			foreach($aryparam as $key =>$value)
			{
				if(is_array($aryValue) && isset($aryValue[$value]) && $value!=$this->tbl_id)
				{
					$aryValue[$value]=str_replace("'","\\'",$aryValue[$value]);
					if($set=='')
					{
						$set=$value."='".$aryValue[$value]."'";
					}
					else
					{
						$set.=",".$value."='".$aryValue[$value]."'";
					}
				}
				else
				{
					continue;
				}
			}
		}

		if($set!='')
		{
			$sql.=$set;
		}
		else
		{
			return false;
		}
		$this->sql=$sql;
		$rs=$this->query($sql);
		if($rs)
		{
			$insertid=$this->insert_id();
			return $insertid;
		}
		else
		{
			return false;
		}
	}
	
	/*
	* 更新新数据 使用前必须设定数据库表的"表名","主键名"
	* @param id			主键值
	* @param where		自定义条件
	* @param aryValue	待插入的值
	* @param tbl 		表名
	* @return Object
	*/
	function Update($id,$where='',$aryValue='',$tbl='')
	{
		if(empty($aryValue))
		{
			$aryValue=$this->value;
		}
		if(empty($tbl))
		{
			$tbl=$this->tbl;
		}
		$sql="update $tbl set ";
		$set='';		//初始化插入数据为空
		if(empty($this->params))
		{
			$this->getParam($tbl);
		}
		$aryparam=explode(',',$this->params);
		if(is_array($aryparam))
		{
			foreach($aryparam as $key =>$value)
			{
				if(is_array($aryValue) && isset($aryValue[$value]) && $value!=$this->tbl_id)
				{
					$aryValue[$value]=str_replace("'","\\'",$aryValue[$value]);
					if($set=='')
					{
						$set=$value."='".$aryValue[$value]."'";
					}
					else
					{
						$set.=",".$value."='".$aryValue[$value]."'";
					}
				}
				else
				{
					continue;
				}
			}
		}
		//生成条件
		$conv='';
		if(!empty($id))
		{
			if(empty($conv))
			{
				$conv=" where {$this->tbl_id}='{$id}'";
			}
			else
			{
				$conv.=" and {$this->tbl_id}='{$id}'";
			}
		}
		if(!empty($where))
		{
			if(empty($conv))
			{
				$conv=" where {$where}";
			}
			else
			{
				$conv.=" and {$where}'";
			}
		}
		if($set!='' && $conv!='')
		{
			$sql.=$set.$conv;
		}
		else
		{
			$sql='';
			$this->sql=$sql;
			return false;
		}
		$this->sql=$sql;
		$rs=$this->query($sql);
		return $rs;
	}
	/** 根据字段名称，表名，条件，取得第一条数据指定字段的值
	* @param $columnName		字段名
	* @param $sql				sql语句
	* @Return String
	*/
	function GetOneVal($columnName,$sql)
	{
		$row=$this->GetOneSql($sql);
		return $row[$columnName];
	}
}

/*******************
面向对象的数据操作类，主要用于操作单条记录
关键参数
tbl				表名
where		查询条件
error		错误日志
querysql	前一次查询数据的sql
savesql		前一次保存数据的sql
data		对象数据
********************/
class MySqlObject
{
	private $error;		//错误日志
	function __construct($data=array())
	{
		if(is_array($data))
		{
			foreach($data as $k => $v)
			{
				$this->setVal($v,$k);
			}
		}
	}
	
	//取得对象的值
	function getVal($param)
	{
		return $this->data[$param];
	}
	
	//设置值
	function setVal($val,$param)
	{
		$this->data[$param]=$val;
	}

	//保存值
	function saveVal($tbl='',$where='')
	{
		global $db;
		if(!empty($tbl))
		{
			$this->tbl=$tbl;
		}
		if(!empty($where))
		{
			$this->where=$where;
		}
		$rs=$db->updateRow($this->tbl,$this->data,$this->where);
		$this->savesql=$db->sql;
		return $rs;
	}
	
	//获取单条数据，并给对象数据赋值
	function query($sql)
	{
		global $db;
		
		if(!empty($sql))
		{
			$this->querysql=$sql;
		}

		$rs=$db->query($this->querysql);
		if($rs && $this->data=$db->fetchRow($rs))
		{
			return true;
		}
		else
		{
			$this->data=array();
			return false;
		}
	}
	
	//获取单条数据，并给对象数据赋值
	function Execute($sql)
	{
		global $db;
		
		if(!empty($sql))
		{
			$this->querysql=$sql;
		}

		$rs=$db->query($this->querysql);
		if($rs && $this->data=$db->fetchRow($rs))
		{
			return true;
		}
		else
		{
			$this->data=array();
			return false;
		}
	}
}

$db = new MySql();
?>